package com.wxgzh.controller;

import cn.hutool.http.HttpUtil;
import org.hibernate.engine.jdbc.StreamUtils;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import sun.net.www.http.HttpClient;

import java.io.*;
import java.nio.charset.StandardCharsets;

@RestController
public class JsonFileReceiverController {

    // 接收JSON文件的POST请求
    //localHost:8089/receiver
    private static final String JSON_FILE_DIR = "JsonFile/";

    @PostMapping("/receiver")
    public ResponseEntity<String> downloadJson(@RequestBody String jsonMessage) {
        // 创建目标文件路径
        String targetFilePath = "src/main/resources/" + JSON_FILE_DIR + "downloadedJson.json";

        // 创建目标文件
        File targetFile = new File(targetFilePath);
        try (InputStream inputStream = new ByteArrayInputStream(jsonMessage.getBytes(StandardCharsets.UTF_8));
             FileOutputStream outputStream = new FileOutputStream(targetFile)) {

            // 将输入流中的数据写入文件
            StreamUtils.copy(inputStream, outputStream);
            outputStream.flush();

            // 返回成功消息
            return ResponseEntity.ok("JSON file downloaded successfully.");
        } catch (IOException e) {
            // 处理异常
            return ResponseEntity.status(500).body("Failed to download JSON file: " + e.getMessage());
        }
    }

    @GetMapping("/download-today-json")
    public void downloadTodayJson(){
        String url = "localhost:8090/download-today-json";
        String result = HttpUtil.get(url);
    }

    public static void main(String[] args) {
        String url = "localhost:8090/download-today-json";
        String result = HttpUtil.get(url);
        System.out.println(1);

    }

    public String doPost(String url,String requestBody){
        String post = HttpUtil.post(url, requestBody);
        return post;
    }

}